package zpx.web;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.compass.core.util.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import org.springframework.web.servlet.ModelAndView;

import zpx.iservice.IComAttachmentService;
import zpx.iservice.IUserService;
import zpx.model.ComAttachment;
import zpx.model.DataDictionaryItem;
import zpx.model.DataDictionaryItems;
import zpx.model.User;
import zpx.util.XMLDDItemParser;


@Controller
@RequestMapping("/user")
public class UserController {
	private IComAttachmentService comAttachmentService;

	public IComAttachmentService getComAttachmentService() {
		return comAttachmentService;
	}
	
	@Resource
	public void setComAttachmentService(IComAttachmentService comAttachmentService) {
		this.comAttachmentService = comAttachmentService;
	}
	private IUserService userService;
	
	public IUserService getUserService() {
		return userService;
	}
	
	@Resource
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	@RequestMapping(value={"/users","/"},method=RequestMethod.GET)
	public String list() {
		//model.addAttribute("pagers", userService.find());
		return "user/list";
	}
	@RequestMapping(value="/getUserList",method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public JSONObject getUserList(HttpServletRequest request, HttpServletResponse response) {
		// 查询条件
        Map<String, String> searchMap = new HashMap<String, String>();
		JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        // 获取页面显示的总数量
        int total = this.userService.getUserCount();
        // 取得的开始记录数
        int startIndex = 0;
        // 每页取得的数量
        int pageSize = 20;
        String rows = request.getParameter("rows");
        String page = request.getParameter("page");
        // 计算分页显示
        if (rows != null && !"".equals(rows) && page != null && !"".equals(page)) {
            int iPage = Integer.parseInt(page);
            pageSize = Integer.parseInt(rows);
            startIndex = (iPage - 1) * pageSize;
            while (startIndex >= total && startIndex > 0) {
                iPage--;
                startIndex = (iPage - 1) * pageSize;
            }
            searchMap.put("startIndex", startIndex + "");
            searchMap.put("pageSize", pageSize + "");
        }
        List<User> datalist=userService.getUserList(searchMap);
        // ����δnull��ҳ��{}������
        if (datalist == null) {
            datalist = new ArrayList<User>();
        }
        // ��������
        if (datalist != null) {
            for (User user : datalist) {
                jsonArray.add(this.getUserToJsonObj(user));
            }
        }
        jsonObject.put("rows", jsonArray);
        jsonObject.put("total", total);
		return jsonObject;
	}
	
	private JSONObject getUserToJsonObj(User user) {
        JSONObject jsonObj = new JSONObject();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 主键
        jsonObj.put("id", user.getId());
        // 昵称
        jsonObj.put("nickname", user.getNickname());
        // 用户名
        jsonObj.put("username", user.getUsername());
        // 邮箱
        jsonObj.put("email", user.getEmail());
        
        if(StringUtils.hasText(user.getPassword())){
        	jsonObj.put("password", user.getPassword());
        }
        
        //创建日期
        if(user.getCreateDate()!=null){
        	 jsonObj.put("createDate", dateFormat.format(user.getCreateDate()));
        }
        if(user.getUpdateDate()!=null){
        	//修改日期
            jsonObj.put("updateDate", dateFormat.format(user.getUpdateDate()));
        }
        
        
       
        return jsonObj;
    }
	
	 /**
     * 用户信息
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/userAddOrUpdate")
    public ModelAndView userAddOrUpdate(HttpServletRequest request,
            HttpServletResponse response) {
    	String operWay=request.getParameter("operWay");
    	
    	Map<String, Object> map = new HashMap<String, Object>();
    	String id=request.getParameter("id");
    	User user=new User();
    	//编辑或查看
    	if(operWay.equals("2")||operWay.equals("3")){
    		
    		user=userService.load(id);
    	}
    	// 附件列表
        List<ComAttachment> attaList = new ArrayList<ComAttachment>();
        if (id != null && !"".equals(id)) {
            // ���Ҫ�޸ĵ���ҵ��Ʊ
            attaList = comAttachmentService.getAttachments(id);
        }
    	
    	DataDictionaryItems usestatusList=XMLDDItemParser.getDataDictionaryItems("UseStatus");
    	List<DataDictionaryItem> dataDictionaryItems=usestatusList.getDataDictioanryItems();
    	map.put("user", user);
    	map.put("comAttachments", attaList);
    	map.put("usestatusList", dataDictionaryItems);
    	if(operWay.equals("3")){
    		return new ModelAndView("user/show",map);
    	}else{
    		return new ModelAndView("user/add",map);
    	}
    }
	
    /**
     * 
     * 保存用户信息
     * @param request
     * @param response
     * @return
     */
	@RequestMapping(value="/add",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> add(HttpServletRequest request, User user,String fileNames,String filePaths,String delComAttIds) {
		/*if(br.hasErrors()) {
			return "user/add";
		}*/
		User loginUser = (User)request.getSession().getAttribute("loginUser");
		Map<String, Object> searchMap=new HashMap<String, Object>();
		searchMap.put("user", user);
		searchMap.put("fileNames", fileNames);
		searchMap.put("filePaths", filePaths);
		searchMap.put("delComAttIds", delComAttIds);
		searchMap.put("loginUser", loginUser);
		userService.saveUpdate(searchMap);
		Map<String, String> returnMap = new HashMap<String, String>();
        returnMap.put("info", "success");
		return returnMap;
	}

	/**
     * 验证码校验
     * @param request
     * @param response
     * @return
     */
	@RequestMapping(value="/checkCode",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> checkCode(HttpServletRequest request) {
		String checkCode=request.getParameter("checkCode");
		Map<String, String> returnMap = new HashMap<String, String>();
		if(checkCode.equalsIgnoreCase((String) request.getSession().getAttribute("randCheckCode"))){
			returnMap.put("info", "success");
		}else{
			returnMap.put("info", "failer");
		}
        
		return returnMap;
	}
	
	@RequestMapping(value="/{id}/delete",method=RequestMethod.GET)
	public String delete(@PathVariable String id) {
		userService.delete(id);
		return "redirect:/user/users";
	}
	///PS：WebDataBinder是用来绑定请求参数到指定的属性编辑器.由于前台传到controller里的值是String类型的，当往Model里Set这个值的时候，如果set的这个属性是个对象，Spring就会去找到对应的EDITOR进行转换，然后再SET进去
	@InitBinder   
    public void initBinder(WebDataBinder binder) {   
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");   
        dateFormat.setLenient(true);   
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   
    } 
}
